package com.ldc.security.filter;

import com.ldc.common.utils.JwtUtils;
import com.ldc.common.utils.RedisUtils;
import com.ldc.common.utils.RequestUtils;
import com.ldc.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 功能说明
 *
 * @auther liudc
 * @since 2023/6/14
 */
@Slf4j
@Component
public class SecurityTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtils redisUtils;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        final String token = RequestUtils.getToken(request);
        log.info("token - {} url - {}", token, request.getRequestURI());
        if (StringUtils.isEmpty(token)) {
            // token 不合法
            filterChain.doFilter(request, response);
            return;
        }
        if (JwtUtils.notAvailable(token)) {
            // token 不可用
            filterChain.doFilter(request, response);
            return;
        }
        //  提取用户名
        final String userName = JwtUtils.getUserName(token);
        log.info("username = {}", userName);
        if (StringUtils.isEmpty(userName)) {
            filterChain.doFilter(request, response);
            return;
        }
        //  设置授权信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        UsernamePasswordAuthenticationToken userToken = new UsernamePasswordAuthenticationToken(userDetails.getUsername()
                , userDetails.getPassword(), userDetails.getAuthorities());
        // 设置认证信息
        SecurityContextHolder.getContext().setAuthentication(userToken);
        filterChain.doFilter(request, response);
    }
}
